package net.freebytes.ssmp.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义认证器
 *
 * @author 千里明月
 * @date 2021/7/20
 **/
public class CusAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(CusAuthenticationFilter.class);

    private boolean defaultLogin = false;

    public CusAuthenticationFilter() {
        super();
    }

    public CusAuthenticationFilter(boolean defaultLogin) {
        super();
        this.defaultLogin = defaultLogin;
    }

    private static final String OPTIONS = "OPTIONS";

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONS
        if (request instanceof HttpServletRequest) {
            if (OPTIONS.equals(((HttpServletRequest) request).getMethod().toUpperCase())) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (defaultLogin) {
                //未登录时  默认使用admin登录
                UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
                return true;
            } else {
                //未登录时  返回403错误
                if (log.isTraceEnabled()) {
                    log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                            "Authentication url [" + getLoginUrl() + "]");
                }
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                servletResponse.setHeader("Access-Control-Allow-Origin", "*");
                servletResponse.setContentType("application/json; charset=utf-8");
                // 自定义返回内容
                servletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                String result = "{\"status\":" + 403 + ", \"msg\":\"未登录\"}";
                servletResponse.getWriter().write(result);
                return false;
            }
        }
    }
}